# -*- coding: utf-8 -*-
# @Time    : 2023/5/25 0025 11:01
# @Author  : zcj
# @File    : dingding.py
# @Software : PyCharm

import time
import hmac
import hashlib
import base64
import urllib.parse
import datetime
import json
import requests

timestamp = str(round(time.time() * 1000))
secret = '密钥'
secret_enc = secret.encode('utf-8')
string_to_sign = '{}\n{}'.format(timestamp, secret)
string_to_sign_enc = string_to_sign.encode('utf-8')
hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
print(timestamp)
print(sign)

url = f'https://oapi.dingtalk.com/robot/send?access_token=64d0f36d9be5c4ab7c210f56ac5f495cc22760e2d7b6f45fa2c90727ce7e43f&timestamp={timestamp}&sign={sign}'


def send_request(url, datas):
    header = {
 "Content-Type": "application/json",
 "Charset": "UTF-8"
    }
    sendData = json.dumps(datas)
    sendDatas = sendData.encode("utf-8")
    request = urllib.request.Request(url=url, data=sendDatas, headers=header)
    opener = urllib.request.urlopen(request)
 # 输出响应结果
    print(opener.read())


def get_string():
 '''
    自己想要发送的内容，注意消息格式，如果选择markdown，字符串中应为包含Markdown格式的内容
    例：
    "<font color=#00ffff>昨日销售额：XXX</font> \n <font color=#00ffff>昨日销量：XXX</font>"
    '''
 return "- 测试1 - 测试2"


def main():
 # isAtAll：是否@所有人，建议非必要别选，不然测试的时候很尴尬
    dict = {
 "msgtype": "markdown",
 "markdown": {"title": "销售日报",
 "text": ""
                     },
 "at": {
 "isAtAll": False
        }
    }

 #把文案内容写入请求格式中
    dict["markdown"]["text"] = get_string()
    send_request(url, dict)


if __name__ == '__main__':

    main()